#include "MoveByCircle.h"

USING_NS_CC;

void MoveByCircle::dumy() {
    MoveBy* move = nullptr;
}

MoveByCircle* MoveByCircle::create(float duration, Vec2 center,
    bool needUpdateCenter, CenterUpdater updater) {
    if ( needUpdateCenter ) {
        CCASSERT(updater != nullptr, "MoveByCircle need updater");
    }
    MoveByCircle* action = new ( std::nothrow ) MoveByCircle();
    if ( action && action->initWithDuration(duration, center) ) {
        action->_needUpdateCenter = needUpdateCenter;
        action->_centerUpdater = updater;
        action->autorelease();
        return action;
    }
    else {
        delete action;
        action = nullptr;
    }
    return action;
}

bool MoveByCircle::initWithDuration(float duration, Vec2 center) {
    bool ret(false);

    if ( ActionInterval::initWithDuration(duration) ) {
        _center = center;
        ret = true;
    }
    return ret;
}

MoveByCircle::MoveByCircle()
: _originRadian(0),
_startPosition(Vec2(0, 0)),
_center(Vec2(0, 0)),
_radius(0),
_needUpdateCenter(false),
_centerUpdater(nullptr) {

}

MoveByCircle::~MoveByCircle() {

}

void MoveByCircle::startWithTarget(Node *target) {
    ActionInterval::startWithTarget(target);
    if ( target ) {
        _startPosition = target->getPosition();
        CCLOG("_startPosition: (%lf, %lf)\n", _startPosition.x, _startPosition.y);
        CCLOG("_center: (%lf, %lf)\n", _center.x, _center.y);
        _radius = sqrt(( _startPosition.x - _center.x ) * ( _startPosition.x - _center.x ) +
            ( _startPosition.y - _center.y ) * ( _startPosition.y - _center.y ));

        CCLOG("_radius: %lf\n", _radius);
        _originRadian = atan(abs(_startPosition.x - _center.x) / abs(_startPosition.y - _center.y));
        CCLOG("_originRadian: %lf, in degree: %lf\n", _originRadian, CC_RADIANS_TO_DEGREES(_originRadian));
    }
}

void MoveByCircle::update(float dt) {
    // dt == percent of the total progress.
    if ( _target ) {
        //_needUpdateCenter ? ( _center = _centerUpdater() ) : nullptr;
        if ( _needUpdateCenter ) {
            _center = _centerUpdater();
        }
        auto newPos = _startPosition.rotateByAngle(_center, 2 * M_PI * dt);
        _target->setPosition(newPos);
    }
}
